﻿using System;
using System.Windows.Input;
using IronCow;
using Milkify.Data;
using Milkify.Interfaces;
using Milkify.Input;

namespace Milkify.Controllers
{
    class AuthenticationController : Controller
    {
        private string mFrob;
        private IAuthenticationView mView;

        public AuthenticationController(ControllerContext context, Rtm rtm, IViewContainer viewContainer, IViewFactory viewFactory)
            : base(context, rtm, viewContainer)
        {
            mView = (IAuthenticationView)viewFactory.Create("Authentication");
        }

        public override void Execute()
        {
            ICommand navigateToAuthorizationCommand = new DecoupledCommand(NavigateToAuthorization);
            ICommand authenticateCommand = new DecoupledCommand(Authenticate);
            var viewData = new AuthenticationViewData(navigateToAuthorizationCommand, authenticateCommand);
            mView.ViewData = viewData;

            ViewContainer.NavigateToView(mView);
        }

        private void NavigateToAuthorization()
        {
            try
            {
                mFrob = Rtm.GetFrob();
            }
            catch (Exception e)
            {
                mView.ErrorMessage = "An error occured while trying to obtain a security token from Remember The Milk: " + e.Message;
                return;
            }

            string authenticationUrl = Rtm.GetAuthenticationUrl(mFrob, AuthenticationPermissions.Delete);
            System.Diagnostics.Process.Start(authenticationUrl);
        }

        private void Authenticate()
        {
            if (string.IsNullOrEmpty(mFrob))
            {
                mView.ErrorMessage = "Please go the authentication URL, authorize this application, and then only click 'Continue'.";
                return;
            }

            User user = null;
            string token = Rtm.GetToken(mFrob, out user);
            if (!string.IsNullOrEmpty(token) && user != null)
            {
                Properties.Settings.Default.Token = token;
                Properties.Settings.Default.Save();

                Rtm.AuthToken = token;

                ViewContainer.UserName = user.UserName;
                mView.Return(true);
            }
        }
    }
}
